package com.example.webviewapplication;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.LinearGradient;
import android.media.MediaDataSource;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Dictionary;
import java.util.Locale;

import static android.app.Activity.RESULT_OK;

public class CustomWebChromeClient extends WebChromeClient {
    private WeakReference<Activity> wkContext;
    private ValueCallback<Uri> mUploadCallBack;
    private ValueCallback<Uri[]> mUploadCallBackAboveL;
    private int REQUEST_PICK = 0x1;
    private int REQUEST_PICK_L = 0x2;
    private int REQUEST_CAPTURE = 0x3;
    private int REQUEST_CAPTURE_L = 0x4;
    private Uri captureUri;
    private String capturePath;

    CustomWebChromeClient(Activity context) {
        wkContext = new WeakReference<>(context);
    }

    @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
        Log.e("webview", consoleMessage.message());
        return super.onConsoleMessage(consoleMessage);
    }

    // For Android  >= 3.0
    public void openFileChooser(ValueCallback valueCallback, String acceptType) {
        openFileChooser(valueCallback, acceptType, null);
    }

    //For Android  >= 4.1
    public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
        showFileChooser(valueCallback, acceptType, capture);
    }


    // For Android >= 5.0
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        return showFileChooserAboveL(webView, filePathCallback, fileChooserParams);
    }

    private void showFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
        mUploadCallBack = valueCallback;
        Intent intentPick;
        Intent intentCapture;
        String captureStr=TextUtils.isEmpty(capture)?"":capture;
        switch (captureStr) {
            case "camera":
                intentCapture = createCaptureIntent("image");
                wkContext.get().startActivityForResult(intentCapture, REQUEST_CAPTURE);
                break;
            case "camrcorder":
                intentCapture = createCaptureIntent("video");
                wkContext.get().startActivityForResult(intentCapture, REQUEST_CAPTURE);
                break;
            case "microphone":
                intentCapture = createCaptureIntent("audio");
                wkContext.get().startActivityForResult(intentCapture, REQUEST_CAPTURE);
                break;
            default:
                intentPick=new Intent();
                intentPick.setType("*/*");
                if (Build.VERSION.SDK_INT < 19) {
                    intentPick.setAction(Intent.ACTION_GET_CONTENT);
                    intentPick.addCategory(Intent.CATEGORY_OPENABLE);
                } else {
                    intentPick.setAction(Intent.ACTION_PICK);
                }
                wkContext.get().startActivityForResult(intentPick, REQUEST_PICK);
                break;
        }


    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private boolean showFileChooserAboveL(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        mUploadCallBackAboveL = filePathCallback;
        String[] types = fileChooserParams.getAcceptTypes();
        String mimeType = types.length == 0 ? "*/*" : types[0];
        if ("*/*".equals(mimeType) || !fileChooserParams.isCaptureEnabled()) {
            Intent intent = fileChooserParams.createIntent();
            wkContext.get().startActivityForResult(intent, REQUEST_PICK_L);
        } else {
            Intent intent ;
            if (mimeType.contains("image")) {
                intent = createCaptureIntent("image");
                wkContext.get().startActivityForResult(intent, REQUEST_CAPTURE_L);
            } else if (mimeType.contains("video")) {
                intent = createCaptureIntent("video");
                wkContext.get().startActivityForResult(intent, REQUEST_CAPTURE_L);
            } else if (mimeType.contains("audio")) {
                intent = createCaptureIntent("audio");
                wkContext.get().startActivityForResult(intent, REQUEST_CAPTURE_L);
            }else{
                Toast.makeText(wkContext.get(),"无法识别的capture类型",Toast.LENGTH_LONG).show();
            }

        }
        return true;
    }

    private Intent createCaptureIntent(String type) {
        SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String filename = timeStampFormat.format(new Date());
        String dictionary = "";
        String action = null;
        switch (type) {
            case "image":
                action = MediaStore.ACTION_IMAGE_CAPTURE;
                capturePath = filename + ".jpeg";
                dictionary = Environment.DIRECTORY_DCIM;
                break;
            case "video":
                action = MediaStore.ACTION_VIDEO_CAPTURE;
                capturePath = filename + ".mp4";
                dictionary = Environment.DIRECTORY_DCIM;
                break;
            case "audio":
                action = MediaStore.Audio.Media.RECORD_SOUND_ACTION;
                capturePath = filename + ".mp3";
                dictionary = Environment.DIRECTORY_MUSIC;
                break;
        }
        boolean b = Build.VERSION.SDK_INT >= 24;
        File file = new File(wkContext.get().getExternalCacheDir(), capturePath);
        if (!file.getParentFile().exists()) {
            file.mkdirs();
        }

        captureUri = b
                ? FileProvider.getUriForFile(wkContext.get(), BuildConfig.APPLICATION_ID + ".fileProvider", file)
                : Uri.fromFile(file);


        Intent intent = new Intent();
        intent.setAction(action);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
        return intent;
    }


    void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Uri pickUri = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (requestCode == REQUEST_PICK || requestCode == REQUEST_CAPTURE) {
            if (requestCode == REQUEST_PICK) {
                mUploadCallBack.onReceiveValue(pickUri);
            }
            if (requestCode == REQUEST_CAPTURE) {
                mUploadCallBack.onReceiveValue(resultCode == RESULT_OK ? pickUri == null ? captureUri : pickUri : null);
            }
        } else if (requestCode == REQUEST_PICK_L || requestCode == REQUEST_CAPTURE_L) {
            if (requestCode == REQUEST_PICK_L) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mUploadCallBackAboveL.onReceiveValue(FileChooserParams.parseResult(resultCode, data));
                }
            }
            if (requestCode == REQUEST_CAPTURE_L) {
                mUploadCallBackAboveL.onReceiveValue(resultCode == RESULT_OK ? new Uri[]{pickUri == null ? captureUri : pickUri} : null);
            }
        }
        mUploadCallBack = null;
        mUploadCallBackAboveL = null;
    }
}